<?php

namespace App\Console\Commands;

use App\Models\AutoMoneyTransaction;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class AutoMoneyTransactionCommand extends Command
{
    /**
     * 命令名称
     *
     * @var string
     */
    protected $signature = 'money:auto-transaction';

    /**
     * 命令描述
     *
     * @var string
     */
    protected $description = '执行定时记账任务';

    /**
     * 执行命令
     */
    public function handle()
    {
        $this->info('开始执行定时记账任务...');
        $now = Carbon::now();
        $this->info('当前时间: ' . $now->toDateTimeString());

        // 获取需要执行的定时记账任务
        $pendingTasks = AutoMoneyTransaction::getPendingTasks($now);
        $this->info('找到 ' . $pendingTasks->count() . ' 个待执行的定时记账任务');

        $successCount = 0;
        $failCount = 0;

        foreach ($pendingTasks as $task) {
            try {
                $transaction = $task->execute($now);
                if ($transaction) {
                    $successCount++;
                    $this->info(
                        "成功执行定时记账: ID={$task->id}, " .
                        "标题={$task->title}, " .
                        "金额={$task->amount}, " .
                        "类型={$task->getTypeTextAttribute()}"
                    );
                } else {
                    $failCount++;
                    $this->error("定时记账执行失败: ID={$task->id}, 标题={$task->title}");
                }
            } catch (\Exception $e) {
                $failCount++;
                $this->error("定时记账执行异常: ID={$task->id}, 标题={$task->title}, 错误: {$e->getMessage()}");
                Log::error("定时记账执行异常", [
                    'task_id' => $task->id,
                    'error' => $e->getMessage(),
                    'trace' => $e->getTraceAsString()
                ]);
            }
        }

        $this->info("定时记账任务执行完成: 成功 {$successCount} 个, 失败 {$failCount} 个");
        return 0;
    }
}
